<?php
namespace app\member\model;

use app\BaseModel;
use app\shop\model\IndexCouponRecord;
use think\facade\Db;

class Coupon extends BaseModel
{
    //会员权益表
    protected $name = 'longbing_card_v2_member_coupon';


    /**
     * @author chenniang
     * @DataTime: 2020-09-07 16:18
     * @功能说明:添加优惠券
     */
    public function addCoupon($coupon, $level_id,$data){

        $this->where(['member_id'=>$level_id])->delete();

        if(!empty($coupon)){

            array_walk($coupon, function ($value, $key) use (&$coupon, $level_id,$data) {

                $coupon[$key] = [
                    //等级id
                    'member_id' => $level_id,

                    'uniacid'   => $data['uniacid'],

                    'coupon_id' => $value['coupon_id'],

                    'num'       => $value['num'],

                ];

            });
            //添加
            $res = $this->saveAll($coupon);

        }

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-08 16:30
     * @功能说明:添加用户的优惠券
     */
    public function insertCoupon($level,$order){

        if($level['coupon_switch']!=1){

            return true;
        }

        $dis = [

            'a.member_id' => $level['id']
        ];

        $data = $this->alias('a')
                ->join('longbing_card_coupon b','a.coupon_id = b.id')
                ->where($dis)
                ->group('a.coupon_id')
                ->field('b.*,a.num as coupon_num')
                ->select()
                ->toArray();

        $record_model = new IndexCouponRecord();

        if(!empty($data)){

            foreach ($data as $coupon){

                for ($i=0;$i<$coupon['coupon_num'];$i++){

                    if(!isset($order['staff_id'])&&isset($order['to_uid'])){

                        $order['staff_id'] = $order['to_uid'];
                    }
                    //领取优惠券
                    $record_model->insertRecord($coupon,$order);

                }

            }
        }

        return true;
    }









}